package com.sea.app.module.identity;

import com.sea.app.common.excrption.SystemException;
import com.sea.app.module.identity.domain.algorithm.JwtToken;
import com.sea.app.common.kit.ServletRequests;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by 31417 on 2017/4/27.
 */
//@WebFilter(urlPatterns = "/*",filterName="myFilter")
public class SecurityFilter implements Filter {
    private static final String AUTH_HEADER =  "X-Authorization";

    @Value("${security.path.exclude}")
    private String[] exclude;

    @Value("${security.key}")
    private String key;


    private OrRequestMatcher orRequestMatcher;

    private boolean isExclude(HttpServletRequest request){
        return orRequestMatcher != null && orRequestMatcher.matches(request);
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if(exclude == null){
            return;
        }
        List<RequestMatcher> antPathRequestMatchers = Arrays.stream(exclude).map(s -> {
            return  new AntPathRequestMatcher(s);
        }).collect(Collectors.toList());
        this.orRequestMatcher = new OrRequestMatcher(antPathRequestMatchers);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(isExclude((HttpServletRequest) servletRequest)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String s = ((HttpServletRequest) servletRequest).getHeader(AUTH_HEADER);
        JwtToken token = JwtToken.on(s,key);
        ServletRequests sr = ServletRequests.on((HttpServletRequest) servletRequest);
        if(token.validateToken(sr.ip())){
            servletRequest.setAttribute("loginName",token.getSubject());
            servletRequest.setAttribute("loginUserId",token.getId());
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        throw SystemException.on("security.tokenValidateFail","验证失败！");
    }

    @Override
    public void destroy() {
    }
}
